package com.siddy.bbs.http;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;

public class VolleyRequest<T> extends Request<T> {

	protected ResponseParser<T> mResponseParser;

	protected ResponseListener<T> mResponseListener;

	public VolleyRequest(int method, String url, ResponseParser<T> responseParser,
			ResponseListener<T> responseListener) {
		super(method, url, responseListener);
		this.mResponseParser = responseParser;
		if (mResponseParser == null) {
			mResponseParser = new EmptyParser<T>();
		}
		this.mResponseListener = responseListener;
	}

	public VolleyRequest(int method, String url) {
		this(method, url, null, null);
	}

	public void addResponseParser(ResponseParser<T> responseParser) {
		mResponseParser = responseParser;
	}

	public void addResponseListener(ResponseListener<T> responseListener) {
		mResponseListener = responseListener;
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		Response<T> resp = mResponseParser.parse(response);
		if (mResponseListener != null) {
			mResponseListener.onResponseBackground(resp);
		}
		return resp;
	}

	@Override
	protected void deliverResponse(T response) {
		if (mResponseListener != null) {
			mResponseListener.onResponse(response);
		}
	}

	private static class EmptyParser<T> implements ResponseParser<T> {

		@Override
		public Response<T> parse(NetworkResponse response) {
			return Response.success(null, null);
		}

	}

}
